package com.example.luyennghe;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

public class LoginActivity extends Activity{
    private EditText edtUsername;
    private EditText edtPassword;
    private ImageButton imgbtnLogin;
    private ImageButton imgbtnRegister;
    private ProgressDialog pDialog;
    
    private String username = "";
    private String password = "";
    private String email = "";
    private String hoten = "";
    private String gioitinh = "";
    private String ngaysinh = "";
    private String ngaydangky = "";
    
    private static String urlLogin = "http://huynh.cu.cc/android-server/login.php";
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_MESSAGE = "message";
    private static final String TAG_EMAIL = "email";
    private static final String TAG_HOTEN = "hoten";
    private static final String TAG_NGAYSINH = "ngaysinh";
    private static final String TAG_NGAYDANGKY = "ngaydangky";
    private static final String TAG_GIOITINH = "gioitinh";
    
    private JSONParser jParser = new JSONParser();
    private boolean login_Success = false;
    private boolean login_NoUserFound = false;
    private boolean login_ErrorConnect = false;
    private UserInfo user = new UserInfo();
    
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_layout);
        edtUsername = (EditText)findViewById(R.id.edtUsername);
        edtPassword = (EditText)findViewById(R.id.edtPassword);
        imgbtnRegister = (ImageButton)findViewById(R.id.register);
        imgbtnLogin = (ImageButton)findViewById(R.id.Login);
        imgbtnLogin.setOnClickListener(btnLogin);
        imgbtnRegister.setOnClickListener(btnRegister);        
    }
    ImageButton.OnClickListener btnLogin = new OnClickListener() {
        
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            //check neu username va pass bo trong
            if(edtUsername.getText().toString().equals("")|| edtPassword.getText().toString().equals("")){
                AlertDialog.Builder builder = new AlertDialog.Builder(
                        LoginActivity.this);
                builder.setTitle("Lỗi")
                        .setMessage("Đề nghị nhập đầy đủ thông tin.")
                        .setCancelable(false)
                        .setIcon(R.drawable.warning_icon)
                        .setPositiveButton("OK",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog,
                                            int id) {
                                        dialog.dismiss();
                                    }
                                });
                AlertDialog alert = builder.create();
                alert.show();
            }
            else{
                username = edtUsername.getText().toString();
                password = edtPassword.getText().toString();
                loginHandler();
            }
        }
    };
    ImageButton.OnClickListener btnRegister = new OnClickListener() {
        
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent in = new Intent(getApplicationContext(), RegisterActivity.class);
            startActivity(in);
        }
    };
    class LoginClass extends AsyncTask<String, String, String> {
         
        @Override
        protected void onPreExecute() {
            super.onPreExecute();      
            pDialog = new ProgressDialog(LoginActivity.this);
            pDialog.setMessage("Đang kết nối đến server. Vui lòng đợi...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }
 
        protected String doInBackground(String... args) {
            // Building Parameters            
            List<NameValuePair> paramsLogin = new ArrayList<NameValuePair>();
            paramsLogin.add(new BasicNameValuePair("username", username));   
            paramsLogin.add(new BasicNameValuePair("password", password)); 
            JSONObject json = new JSONObject();
            // getting JSON string from URL
            try {               
                //gui du lieu len server                
                json = jParser.makeHttpRequest(urlLogin, "POST",
                        paramsLogin);
                Log.d("login: ", json.toString());
                // Check SUCCESS TAG
                int success = json.getInt(TAG_SUCCESS);
                String mes = json.getString(TAG_MESSAGE);
                if (success == 1 && mes.equals("OK")) {
                    login_Success = true;
                    email = json.getString(TAG_EMAIL);
                    hoten = json.getString(TAG_HOTEN);
                    gioitinh = json.getString(TAG_GIOITINH);
                    ngaysinh = json.getString(TAG_NGAYSINH);
                    ngaydangky = json.getString(TAG_NGAYDANGKY);
                }
                else
                {
                    if(success==0 && mes.equals("No user found")){
                        login_NoUserFound = true;
                    }
                    else{
                        login_ErrorConnect = true;
                    }
                }
                    
            } 
            catch (Exception ex) {
                Toast.makeText(getApplicationContext(), "Có lỗi xảy ra. " + ex.toString(), Toast.LENGTH_SHORT).show();
            }
            return null;
        }
         
        protected void onPostExecute(String file_url) {
            // updating UI from Background Thread
            pDialog.dismiss();
            if(login_Success){
                login_Success = false;
                user.setUsername(username);
                user.setPassword(password);
                user.setEmail(email);
                user.setHoTen(hoten);
                user.setGioiTinh(gioitinh);
                user.setNgaySinh(ngaysinh);
                user.setNgayDangKy(ngaydangky);
                Intent in = new Intent(getApplicationContext(), MainActivity.class);
                in.putExtra("userinfo", user);
                startActivity(in);
                finish();
            }
            if(login_NoUserFound) 
            {
                login_NoUserFound = false;
                AlertDialog.Builder builder = new AlertDialog.Builder(
                        LoginActivity.this);
                builder.setTitle("Lỗi")
                        .setMessage("Username hoặc password không đúng. Xin hãy thử lại.")
                        .setCancelable(false)
                        .setIcon(R.drawable.warning_icon)
                        .setPositiveButton("OK",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog,
                                            int id) {
                                        dialog.dismiss();
                                    }
                                });
                AlertDialog alert = builder.create();
                alert.show();
            }
            if(login_ErrorConnect){
                login_ErrorConnect = false;
                AlertDialog.Builder builder = new AlertDialog.Builder(
                        LoginActivity.this);
                builder.setTitle("Lỗi")
                        .setMessage("Không thể kết nối đến server.")
                        .setCancelable(false)
                        .setIcon(R.drawable.warning_icon)
                        .setPositiveButton("OK",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog,
                                            int id) {
                                        dialog.dismiss();
                                    }
                                });
                AlertDialog alert = builder.create();
                alert.show();
            }
        }
    }
    public void loginHandler(){             
        if(!checkInternetConnection()){
            AlertDialog.Builder builder = new AlertDialog.Builder(
                    LoginActivity.this);
            builder.setMessage(
                    "Không có kết nối internet. Xin hãy thử lại.")
                    .setCancelable(false)
                    .setTitle("Lỗi")
                    .setIcon(R.drawable.warning_icon)
                    .setPositiveButton("OK",
                            new DialogInterface.OnClickListener() {
                                public void onClick(
                                        DialogInterface dialog, int id) {
                                    dialog.dismiss();
                                }
                            });
            AlertDialog alert = builder.create();
            alert.show();
        }
        else{
            final LoginClass lg = new LoginClass();
            lg.execute();
            Handler _handler = new Handler();
            _handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (lg.getStatus() == AsyncTask.Status.RUNNING) {
                        lg.cancel(true);
                        pDialog.dismiss();
                        AlertDialog.Builder builder = new AlertDialog.Builder(
                                LoginActivity.this);
                        builder.setMessage(
                                "Time out. Xin hãy thử lại.")
                                .setCancelable(false)
                                .setTitle("Lỗi")
                                .setIcon(R.drawable.warning_icon)
                                .setPositiveButton("OK",
                                        new DialogInterface.OnClickListener() {
                                            public void onClick(
                                                    DialogInterface dialog, int id) {
                                                dialog.dismiss();
                                            }
                                        });
                        AlertDialog alert = builder.create();
                        alert.show();
                    }
    
                }
            }, 30000); // timeout sau ... giây sẽ hiện thông báo không kết nối được.
        }
    }
    // kiểm tra kết nối internet
    private boolean checkInternetConnection() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo[] netInfo = cm.getAllNetworkInfo();
        // kiểm tra kết nối wifi và mobile(3G)
        for (NetworkInfo ni : netInfo) {
            if (ni.getTypeName().equalsIgnoreCase("WIFI"))
                if (ni.isConnected())
                    return true;
            if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
                if (ni.isConnected())
                    return true;
        }
        if (cm.getActiveNetworkInfo() != null
                && cm.getActiveNetworkInfo().isAvailable()
                && cm.getActiveNetworkInfo().isConnected()) {
            return true;
        }
        return false;
    }
}
